import { useEffect, useState } from 'react';
import { Drawer, Button, Collapse, Pagination, Spin, message, Space } from 'antd';
import { page as fetchWritingList, addToArchive } from '@/apis/front/document';
import { useNavigate } from 'react-router-dom';

const { Panel } = Collapse;

const PAGE_SIZE = 10;

const parseHtmlContent = (html: string) => {
  if (!html) return '';
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const text = doc.body.textContent || '';
    return text.length > 200 ? text.slice(0, 200) + '...' : text;
  } catch (error) {
    console.error('Error parsing HTML:', error);
    return html.length > 200 ? html.slice(0, 200) + '...' : html;
  }
};

const WritingHistory = ({ visible, onClose, onSelect }) => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [pageNum, setPageNum] = useState(1);
  const navigate = useNavigate();

  useEffect(() => {
    if (visible) {
      loadList(pageNum);
    }
  }, [visible, pageNum]);

  const loadList = async (pageNum) => {
    setLoading(true);
    try {
      const res = await fetchWritingList(pageNum, PAGE_SIZE);
      const data = (res as any).data || {};
      setList(data.records || []);
      setTotal(data.total || 0);
    } finally {
      setLoading(false);
    }
  };

  const handleAddToArchive = async (item) => {
    try {
      const res = await addToArchive(item.id);
      if (res.status && res.data.success) {
        message.success(
          <span>
            添加成功，
            <a onClick={() => navigate('/app/docArchive')}>查看</a>
          </span>
        );
      } else {
        message.error("数据不存在")
      }
    } catch (error) {
      message.error('添加到知识库失败');
    }
  };

  return (
    <Drawer
      title="写作历史"
      placement="right"
      width={400}
      onClose={onClose}
      open={visible}
      destroyOnClose
    >
      <Spin spinning={loading}>
        <Collapse accordion>
          {list.map(item => (
            <Panel header={item.title || '无标题'} key={item.id}>
              <div style={{ marginBottom: 8 }}>
                <div>主题词：{item.keywords}</div>
                <div>创建时间：{item.createTime}</div>
                <div style={{ margin: '8px 0' }}>
                  <Space>
                    <Button type="primary" onClick={() => onSelect(item)}>
                      应用
                    </Button>
                    <Button onClick={() => handleAddToArchive(item)}>
                      添加到知识库
                    </Button>
                  </Space>
                </div>
                <div style={{ maxHeight: 120, overflow: 'auto', color: '#888', fontSize: 12 }}>
                  {parseHtmlContent(item.content) || '无内容'}
                </div>
              </div>
            </Panel>
          ))}
        </Collapse>
        <Pagination
          style={{ marginTop: 16, textAlign: 'right' }}
          current={pageNum}
          pageSize={PAGE_SIZE}
          total={total}
          onChange={setPageNum}
          size="small"
        />
      </Spin>
    </Drawer>
  );
};

export default WritingHistory; 